<template>
  <!--富文本编辑器-->
  <div class="tinymce-editor">
    <el-upload
      class="upload-img"
      ref="uploadimg"
      action="#"
      :http-request="fileUpload"
      :on-change="uploadimgchange"
      :auto-upload="true"
      accept=".jpg, .png">
      <el-button slot="trigger" size="small" type="primary" icon="el-icon-picture" class="upload-btn"></el-button>
    </el-upload>
    <el-upload
      class="upload-img"
      ref="uploadvideo"
      action="#"
      :http-request="fileUpload"
      :on-change="uploadvideochange"
      :auto-upload="true"
      accept=".mp4">
      <el-button slot="trigger" size="small" type="primary" icon="el-icon-picture" class="upload-video"></el-button>
    </el-upload>

    <editor :id="editordata.qeref" v-model = "editordata.content" :init="init" :disabled="disabled" @onChange="onChange"></editor>
  </div>
</template>

<script type="text/ecmascript-6">
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import 'tinymce/themes/silver/theme'

import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/table'
import 'tinymce/plugins/image'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/media'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/anchor'
import 'tinymce/plugins/link'

tinymce.PluginManager.add('imageSelector', function(editor, url) {
  editor.ui.registry.addButton('imageSelector', {
    text: `<span class="tox-icon tox-tbtn__icon-wrap"><svg width="24" height="24"><path d="M5 15.7l3.3-3.2c.3-.3.7-.3 1 0L12 15l4.1-4c.3-.4.8-.4 1 0l2 1.9V5H5v10.7zM5 18V19h3l2.8-2.9-2-2L5 17.9zm14-3l-2.5-2.4-6.4 6.5H19v-4zM4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 0 1-1-1V4c0-.6.4-1 1-1zm6 8a2 2 0 1 0 0-4 2 2 0 0 0 0 4z" fill-rule="nonzero"></path></svg></span>`,
    tooltip:"插入图片",
    onAction: function () {
      editor.settings.imageSelectorCallback(function(r){
          // console.log('inserting image to editor: '+ r.url);
          editor.execCommand('mceInsertContent', false, '<img alt="" src="' + r.url + '" data-size="'+r.size+'" data-index="'+r.index+'"/>');
          imageSelector = ''
      });
      document.querySelector('.upload-img .upload-btn').click();
    }
  });

});
var imageSelector;
var imageSelectedCallback = null;
function showImageSelector(cb){
    imageSelectedCallback = cb;
}
function insertImage(){
    imageSelectedCallback(imageSelector);   // 调用插件内部回调把图片插入到编辑器中
}

tinymce.PluginManager.add('videoSelector', function(editor, url) {
  editor.ui.registry.addButton('videoSelector', {
    text: `<span class="tox-icon tox-tbtn__icon-wrap"><svg width="24" height="24"><path d="M4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 0 1-1-1V4c0-.6.4-1 1-1zm1 2v14h14V5H5zm4.8 2.6l5.6 4a.5.5 0 0 1 0 .8l-5.6 4A.5.5 0 0 1 9 16V8a.5.5 0 0 1 .8-.4z" fill-rule="nonzero"></path></svg></span>`,
    tooltip:"插入视频",
    onAction: function () {
      document.querySelector('.upload-img .upload-video').click();
    }
  });

});


export default {
  components: { editor: Editor },
  props: {
    editordata: {
      type: [Object, Array],
      default: () => {
        return {
          qeref: 'myTinymceEditor',
          content: '',
        };
      }
    }
  },
  data() {
    return {
      // 定义富文本编辑器显示
      selector: '#'+this.editordata.qeref,
      init: {
        theme: "silver",
        skin: 'oxide',
        skin_url: '../static/tinymce/skins/ui/oxide',
        language_url: '../static/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        height: 500,
        browser_spellcheck: true, // 拼写检查
        branding: false, // 去水印
        statusbar: false, // 隐藏编辑器底部的状态栏
        paste_data_images: false, // 允许粘贴图像
        menubar: false, // 隐藏最上方menu
        // custom_undo_redo: true,
        // custom_undo_redo_levels: false,
        // custom_undo_redo_keyboard_shortcuts: false,
        plugins: 'advlist table imagetools imageSelector lists videoSelector paste preview fullscreen anchor link',
        toolbar:
          'fontselect fontsizeselect forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | imageUpload quicklink h2 h3 blockquote table numlist bullist | link anchor imageSelector videoSelector preview fullscreen removeformat',
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '默认字体=sans-serif;微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC;苹果苹方=PingFang SC,Microsoft YaHei;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei;Arial=arial,helvetica;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
        imageSelectorCallback: showImageSelector,  // 点击编辑器上的图片按钮后的回调方法
        media_filter_html: false,
        media_live_embeds: true,
      },
      disabled: false,
      oldimage: [],
      oldvideo: [],
      images: [],
      allsize: 0,
      videos: [],
      neweditsrc: [],
      datahistory: '',
    };
  },
  computed: {
    content() {
      return this.editordata.content;
    },
  },
  destroyed () {
    
  },
  created(){
    this.$nextTick(()=>{
      setTimeout(()=>{
        this.getautodata()
      },1000)
    })
  },
  methods: {
    //提取图片和视频的自定义属性
    getautodata () {
      let videos = []
      let images = []
      let count = 0;
      var obj=document.getElementById("documentbody_ifr").contentWindow; 
      let img = obj.document.querySelectorAll('#tinymce img')
      let video = obj.document.querySelectorAll('#tinymce video')

      for (let g = 0; g < img.length; g++) {
        images.push({
          index: img[g].getAttribute('data-index'),
          size: Number(img[g].getAttribute('data-size')),
          file: img[g].getAttribute('src'),
          type: 'image'
        })
        count+=Number(img[g].getAttribute('data-size'))
      }
      for (let o = 0; o < video.length; o++) {
        videos.push({
          index: video[o].getAttribute('data-index'),
          size: Number(video[o].getAttribute('data-size')),
          file: video[o].getAttribute('src'),
          type: 'video'
        })
        count+=Number(video[o].getAttribute('data-size'))
      }
      this.videos = videos
      this.images = images
      this.allsize = count
      this.neweditsrc = [...images,...videos]
    },
    //添加或删除图片或视频之后重新改变索引值
    changeindex () {
      let videos = []
      let images = []
      let count = 0;
      var obj=document.getElementById("documentbody_ifr").contentWindow; 
      let img = obj.document.querySelectorAll('#tinymce img')
      let video = obj.document.querySelectorAll('#tinymce video')

      for (let g = 0; g < img.length; g++) {
        img[g].setAttribute('data-index',g)
        images.push({
          index: g,
          size: Number(img[g].getAttribute('data-size')),
          file: img[g].getAttribute('src'),
          type: 'image'
        })
        count+=Number(img[g].getAttribute('data-size'))
      }
      for (let o = 0; o < video.length; o++) {
        video[o].setAttribute('data-index',o)
        videos.push({
          index: o,
          size: Number(video[o].getAttribute('data-size')),
          file: video[o].getAttribute('src'),
          type: 'video'
        })
        count+=Number(video[o].getAttribute('data-size'))
      }
      this.videos = videos
      this.images = images
      this.allsize = count
      this.neweditsrc = [...images,...videos]
    },
    // 上传图片
    uploadimgchange (file, filelist) {
      // console.log(file)
      // return false;
      let _this = this
      const isLt5M = file.size / 1024 / 1024 < 5;
      const isLt5G = _this.allsize / 1024 / 1024 / 1024 < 5
      if (!isLt5M || !isLt5G) {
        if (!isLt5M) {
          _this.$message.error('上传图片大小不能超过 5MB!');
        }
        if (!isLt5G) {
          _this.$message.error('上传所有文件大小总和不能超过 5G!');
        }
      } else {
        _this.allsize+=file.size

        // let URL = window.URL || window.webkitURL;
        // let src = URL.createObjectURL(file.raw);

        var obj=document.getElementById("documentbody_ifr").contentWindow; 
        let img = obj.document.querySelectorAll('#tinymce img')


        let data = new FormData()
        let arr = []
        data.append('uploadFiles',file.raw)
        arr.push(img.length)
        data.set('fileIndex',arr)

        _this._API.knowledgeeditor(data).then(res=>{
          // console.log(res.data.data)
          if (res.data.data != null) {
            imageSelector = {
              url: res.data.data[0].file,
              size: file.size,
              index: img.length
            }
            insertImage()
          }
        }).catch(err=>{})
      }
    },
    // 上传视频
    uploadvideochange(file, filelist){
      // console.log(file)
      // return false;
      let _this = this
      const isLt300M = file.size / 1024 / 1024 < 300;
      const isLt5G = _this.allsize / 1024 / 1024 / 1024 < 5
      if (!isLt300M || !isLt5G) {
        if (!isLt300M) {
          _this.$message.error('上传视频大小不能超过 300MB!');
        }
        if (!isLt5G) {
          _this.$message.error('上传所有文件大小总和不能超过 5G!');
        }
      } else {
        _this.allsize+=file.size

        // let URL = window.URL || window.webkitURL;
        // let src = URL.createObjectURL(file.raw);

        var obj=document.getElementById("documentbody_ifr").contentWindow; 
        let video = obj.document.querySelectorAll('#tinymce video')

        let data = new FormData()
        let arr = []
        data.append('uploadFiles',file.raw)
        arr.push(video.length)
        data.set('fileIndex',arr)

        _this._API.knowledgeeditor(data).then(res=>{
          // console.log(res.data.data)
          if (res.data.data != null) {
            videoSelector = {
              url: res.data.data[0].file,
              size: file.size,
              index: video.length
            }
            // insertVideo()
             tinyMCE.editors[this.editordata.qeref].insertContent(`<p>
                <span class="mce-preview-object mce-object-video" contenteditable="false" data-mce-object="video" data-mce-p-allowfullscreen="allowfullscreen" data-mce-p-frameborder="no" data-mce-p-scrolling="no" data-mce-p-src=${res.data.data[0].file} data-mce-html="%20">
                  <video src=${res.data.data[0].file} width="100%" controls="controls" data-size=${file.size} data-index=${video.length}></video>
                </span>
              </p><p></p>`)
          }
        }).catch(err=>{})
      }
    },
    // 删除图片
    uploadRemove(allimg) {
      let images = this.images
      let _this = this
      if (this.images.length == 0) {
        return false;
      }
      var ar = images.filter(function(n) {
        return allimg.indexOf(n.index) == -1
      });
      _this.allsize-=ar[0].size
      
      let data = new FormData()
      data.append('needDeleteFile',images[ar[0].index].file)
      _this._API.knowledgeeditor(data).then(res=>{
        images.splice(ar[0].index, 1);
        // console.log(images)
        _this.changeindex()
      }).catch(err=>{})
    },
    // 删除视频
    removeVideo(allvideo) {
      let videos = this.videos
      let _this = this
      if (this.videos.length == 0) {
        return false;
      }
      var ar = videos.filter(function(n) {
        return allvideo.indexOf(n.index) == -1
      });
      _this.allsize-=ar[0].size
      
      let data = new FormData()
      data.append('needDeleteFile',images[ar[0].index].file)
      _this._API.knowledgeeditor(data).then(res=>{
        // console.log(res.data.data)
        videos.splice(ar[0].index, 1);
        // console.log(videos)
        _this.changeindex()
      }).catch(err=>{})
      // console.log(videos)
      // console.log(videofiles)
    },
    // 自定义上传
    fileUpload(file) {
      // this.imagefiles[file.file.uid+''] = file.file
    },
    // 内容改变事件
    onChange(e) {
      // console.log(e)
      var obj=document.getElementById("documentbody_ifr").contentWindow; 
      let img = obj.document.querySelectorAll('#tinymce img')
      let video = obj.document.querySelectorAll('#tinymce video')
      if (img.length < this.images.length) {
        let arr = []
        for (let i = 0; i < img.length;i++) {
          if (img[i].getAttribute('data-index')) {
            arr.push(Number(img[i].getAttribute('data-index')))
          }
        }
        this.uploadRemove(arr)
      } else if (img.length > this.images.length) {
        this.changeindex()
      }
      if (video.length < this.videos.length) {
        let ar = []
        for (let j = 0; j < video.length;j++) {
          if (video[j].getAttribute('data-index')) {
            ar.push(Number(video[j].getAttribute('data-index')))
          }
        }
        this.removeVideo(ar)
      } else if (video.length > this.videos.length) {
        this.changeindex()
      }
      // this.$emit("editor", { qeref: this.editordata.qeref });
      this.$emit("editor", { qeref: this.editordata.qeref, neweditsrc: this.neweditsrc });
    },
    onKeyDown(e) {
      let _this = this
      var ev=document.getElementById("documentbody_ifr").contentWindow.event||e;
      if((ev.ctrlKey) && (ev.keyCode==67 || ev.keyCode==88 || ev.keyCode==89 || ev.keyCode==90)){
        _this.editordata.content = _this.datahistory
        ev.preventDefault()
        ev.stopPropagation()
      } else {
        _this.datahistory = _this.content
      }
    },
    clear() {
      this.editordata.content = "";
    }
  },
  mounted() {
    tinymce.init({});
  }
};
</script>

<style scoped>
.upload-img {
  display: none;
}
</style>
